﻿using com.tanlingyun.baojia.Entity;
using com.tanlingyun.ViewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.tanlingyun.DbServices
{
    public class SysService : BaseService
    {
        /// <summary>
        /// 创建还原点
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="backup"></param>
        /// <returns></returns>
        public OperateResult CreateBackupPoint(int user_id, BackupRecords backup)
        {
            backup.Time = DateTime.Now;

            string dir = System.Web.HttpContext.Current.Server.MapPath("/") + "DBBackup/";
            //判断目录是否存在
            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
            string path = Guid.NewGuid().ToString().Replace("-", "") + ".sql";

            V_DBInfo dbinfo = GetDbInfo;
            if (dbinfo == null || string.IsNullOrWhiteSpace(dbinfo.Host) || string.IsNullOrWhiteSpace(dbinfo.Port) || string.IsNullOrWhiteSpace(dbinfo.UserID))
                return new OperateResult() { code = ResultCode.Failed, message = "数据库连接信息获取失败！" };

            //构建执行的命令
            //String command = string.Format("mysqldump --host={0} --port={1} --user={2} --password={3} --databases {4} -R >{5}", dbinfo.Host, dbinfo.Port, dbinfo.UserID, dbinfo.Password, helper.UtilityHelper.GetConfig("dbname"), dir + path);
            string command = string.Format("mysqldump --opt -u{0} {1} {2} >{3}",dbinfo.UserID, (string.IsNullOrWhiteSpace(dbinfo.Password)?"": "-p" + dbinfo.Password), helper.UtilityHelper.GetConfig("dbname"), dir + path);
            //获取mysqldump.exe所在路径
            String appDirecroty = helper.UtilityHelper.GetConfig("mysqlbin");
            
            StartCmd(appDirecroty, command);
            backup.Backup_user = user_id;
            backup.Backup_file = dir + path;
            if (db.Insert<BackupRecords>("BackupRecords", backup).AutoMap(x=>x.ID).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed, message = "备份失败！" };
        }

        /// <summary>
        /// 获取备份记录
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<BackupRecords> Backuplist(int user_id, int PageIndex = 1, int PageSize = 10)
        {
            PageInfo<BackupRecords> rdpage = new PageInfo<BackupRecords>()
            {
                Fields = "*",
                TableName = "BackupRecords",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "ID desc"
            };
            string where = "Status = 1";
            rdpage.Where = where;
            return GetPageInfo<BackupRecords>(rdpage);
        }

        /// <summary>
        /// 删除备份
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperateResult DeleteBackup(int user_id,int id)
        {
            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.level_type != (int)ELevelType.Admin)
                return new OperateResult() { code = ResultCode.Failed,message = "只有超级管理员才能完成此操作！" };
            BackupRecords rd = GetRecord(id);
            if (rd == null || rd.Status != 1)
                return new OperateResult() { code = ResultCode.Failed,message = "删除的备份不存在！" };
            rd.Status = 0;
            if (db.Update<BackupRecords>("BackupRecords", rd).Column(x => x.Status).Where(x => x.ID).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed,message = "删除失败！" };
        }

        /// <summary>
        /// 还原数据库
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperateResult RestoreBackup(int user_id,int id)
        {
            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.level_type != (int)ELevelType.Admin)
                return new OperateResult() { code = ResultCode.Failed, message = "只有超级管理员才能完成此操作！" };
            BackupRecords rd = GetRecord(id);
            if (rd == null || rd.Status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "待还原的备份不存在！" };
            if (string.IsNullOrWhiteSpace(rd.Backup_file) || !System.IO.File.Exists(rd.Backup_file))
                return new OperateResult() { code = ResultCode.Failed,message = "备份信息有误，无法还原！" };

            V_DBInfo dbinfo = GetDbInfo;
            if (dbinfo == null || string.IsNullOrWhiteSpace(dbinfo.Host) || string.IsNullOrWhiteSpace(dbinfo.Port) || string.IsNullOrWhiteSpace(dbinfo.UserID))
                return new OperateResult() { code = ResultCode.Failed, message = "数据库连接信息获取失败！" };
            string command = string.Format("mysql -u{0} {1} {2} < {3}", dbinfo.UserID, (string.IsNullOrWhiteSpace(dbinfo.Password) ? "" : "-p" + dbinfo.Password), helper.UtilityHelper.GetConfig("dbname"), rd.Backup_file);
     
            //获取mysqldump.exe所在路径
            String appDirecroty = helper.UtilityHelper.GetConfig("mysqlbin");

            StartCmd(appDirecroty, command);

            return new OperateResult() { code = ResultCode.Success, message = "还原成功！" };
        }

        public OperateResult InitOperatorData(int user_id,int init_user)
        {
            UserService _userService = new UserService() { };
            User init = _userService.GetUser(init_user);
            if (init == null | init.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户不存在！" };
            if (init.level_type != (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "无法初始化非操作员数据！" };

            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户身份有误，请重新登录！" };

            if (entityUser.level_type != (int)ELevelType.Admin && init.parentid != entityUser.id)
                return new OperateResult() { code = ResultCode.Failed, message = "没有权限初始化该用户！" };

            db.Sql("update products set status=0 where add_user=@0", init_user).Execute();

            return new OperateResult() { code = ResultCode.Success };
        }

        public BackupRecords GetRecord(int id)
        {
            return db.Sql("select * from BackupRecords where ID=@0", id).QuerySingle<BackupRecords>();
        }

        /// <summary>
        /// 执行Cmd命令
        /// </summary>
        /// <param name="workingDirectory">要启动的进程的目录</param>
        /// <param name="command">要执行的命令</param>
        public static void StartCmd(String workingDirectory, String command)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.WorkingDirectory = workingDirectory;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            
        }
    }
}
